package chapter43;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatabaseImpl extends UnicastRemoteObject implements Database {

    //
    // DONE:
    //
    ArrayList<Student> studentsal = new ArrayList<Student>();

    public DatabaseImpl() throws RemoteException {
    }

    @Override
    public Student create() throws RemoteException {
        return new StudentImpl();
    }

    @Override
    public void register(Student student) throws RemoteException {
        Student s = search(student.getId());
        if (s == null) {
            studentsal.add(student);

            System.out.println("Register: student " + student.getId());
        }
        else {
            s.setName(student.getName());
            s.setGraduate(student.getGraduate());
            s.setDepartment(student.getDepartment());
            s.setEmail(student.getEmail());
            s.setPhone(student.getPhone());

            System.out.println("Replace: student " + student.getId());
        }
    }

    @Override
    public Student search(int id) throws RemoteException {
        for (Iterator<Student> it = studentsal.iterator(); it.hasNext();) {
            Student student = it.next();
            if (student.getId() == id) {
                return student;
            }
        }

        return null;
    }
}
